//
//  NQAddRecordVc.m
//  ZLFastDoctor
//
//  Created by 李岚清 on 16/5/24.
//  Copyright © 2016年 LS. All rights reserved.
//

#import "NQAddRecordVc.h"
#import "NQDescribeBtn.h"
#import "OKSickTreatController.h"
#import "OKSickSearchController.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "OKSickSearchController.h"
#import "OKSickModel.h"
#import "OKSickComplicationController.h"
#import "OKSickDescVcTableViewController.h"
#import "NQTextView.h"
#import "NQRecord.h"
#import "UIImage+scallImage.h"
#define NQSickLabelH 30
#define NQHolder @"请描述疾病的主要症状,患病时间及治疗情况"
#define NQPicW 80

@interface NQAddRecordVc () <OKSickTreatControllerDelegate, OKSickSearchControllerDelegate, OKSickDescVcTableViewControllerDelegate,UITextViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
/*疾病类型Button*/
@property (weak, nonatomic) IBOutlet UIButton *sickTypeBtn;
/*疾病类型Label*/
@property (weak, nonatomic) IBOutlet UILabel *sickTypeLabel;
/*疾病细分Button*/
@property (weak, nonatomic) IBOutlet UIButton *sickDetailBtn;
/*疾病细分Label*/
@property (weak, nonatomic) IBOutlet UILabel *sickDetailLabel;

@property (assign, nonatomic) NSInteger ci1_id;


/*添加病症描述的大view*/
@property (weak, nonatomic) IBOutlet UIView *addSickDiscribeView;
/*病症描述view*/
@property (weak, nonatomic) IBOutlet UIView *sickDiscribeView;
/*病症描述view的高度约束*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *sickViewHeight;

/*病症label*/
@property (nonatomic, strong) UILabel *label;
/*病症textView*/
@property (weak, nonatomic) IBOutlet NQTextView *describeTextView;

/*装有病历图片的View*/
@property (weak, nonatomic) IBOutlet UIView *sickPicView;


/**
 *  疾病类型
 */
@property (nonatomic, copy) NSString *sickType;
/**
 *  疾病细分
 */
@property (nonatomic, copy) NSString *sickDetail;
/**
 *  疾病描述标签
 */
@property (nonatomic, strong) NSArray *sickDesTags;
/**
 *  疾病描述
 */
@property (nonatomic, copy) NSString *sickDescribe;
/**
 *  病例图片数据源数组
 */
@property (nonatomic, strong) NSMutableArray *picArr;
/**
 *  病例的第一张图片
 */
@property (nonatomic, strong) UIImage *firstImage;
/**
 *  提交病例的当前时间
 */
@property (nonatomic, copy) NSString  *postTime;



@end

@implementation NQAddRecordVc
#pragma mark - set/get
- (void)setRecordSelectedModel:(NQRecord *)recordSelectedModel{
    _recordSelectedModel = recordSelectedModel;
}

- (UIImage *)firstImage{
    if (self.picArr.count > 1) {
        UIImageView *firstImageView = self.picArr[0];
        _firstImage = firstImageView.image;
    }
    return _firstImage;
}

- (NSString *)postTime{
    if (!_postTime) {
        NSDate *nowDate = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *nowTime = [dateFormatter stringFromDate:nowDate];
        _postTime = nowTime;
    }
    return _postTime;
}

- (NSMutableArray *)picArr{
    if (!_picArr) {
        UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [addBtn setBackgroundImage:[UIImage imageNamed:@"AddPic"] forState:UIControlStateNormal];
        [addBtn setBackgroundImage:[UIImage imageNamed:@"compose_pic_add_highlighted"] forState:UIControlStateHighlighted];
        _picArr = [NSMutableArray arrayWithObject:addBtn];
    }
    return _picArr;
}

- (UILabel *)label{
    if (!_label) {
        _label = [[UILabel alloc] init];
        _label.backgroundColor = [UIColor redColor];
    }
    return _label;
}

#pragma mark - View生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置标题
    self.title = @"添加病历";
    
    //设置导航栏右侧按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(confirm)];
    
    //设置文本框
    [self setupTextView];
    
    //设置sickPicView
    [self setupSickPicView];
    
    //给addSickDiscribeView添加手势,用来关闭键盘
    //给头部view添加手势,关闭键盘
    self.addSickDiscribeView.userInteractionEnabled = YES;
    //添加点按手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyBoard)];
    [self.addSickDiscribeView addGestureRecognizer:tap];
}

//关闭键盘
- (void)closeKeyBoard{
    [self.view endEditing:YES];
}

//如果传入了模型,说明外界点击了病例cell
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.recordSelectedModel && !self.isFirst) {
        self.isFirst = YES;
        //疾病类型
        self.sickTypeLabel.text = self.recordSelectedModel.sickType;
        //疾病细分
        self.sickDetailLabel.text = self.recordSelectedModel.sickDetail;
        //布局疾病描述标签
        [self sickDescVcCallBack:self.recordSelectedModel.sickDesTags];
        //疾病描述textView
        self.describeTextView.text = self.recordSelectedModel.sickDescribe;
        [self textViewDidChange:self.describeTextView];
        //病例图片布局
        self.picArr = self.recordSelectedModel.picArr;
        [self setupSickPicView];
        
        UIBarButtonItem *deleteBtn = [[UIBarButtonItem alloc] initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(delete)];
        UIBarButtonItem *postBtn = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(post)];
        self.navigationItem.rightBarButtonItems = @[postBtn,deleteBtn];
    }
}

//点击"删除"按钮
- (void)delete{
    //1.弹出提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定删除这份病历?" message:@"删除后该病历将不再保存,请确认保存后再删除!" preferredStyle:UIAlertControllerStyleAlert];
    
    //2.添加按钮
    //确认
    UIAlertAction *confirmBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([self.delegate respondsToSelector:@selector(didOperation:oldRecord:newRecord:)]) {
            [self.delegate didOperation:NQAddRecordVcTypeDelete oldRecord:self.recordSelectedModel newRecord:nil];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:confirmBtn];
    //取消按钮
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancel];
    
    //3.显示消息框
    [self presentViewController:alert animated:YES completion:nil];
}
//点击"提交"按钮
- (void)post{
    //1.弹出提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提交这份病历?" message:@"保存最新的修改信息!" preferredStyle:UIAlertControllerStyleAlert];
    
    //2.添加按钮
    //确认
    UIAlertAction *confirmBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([self.delegate respondsToSelector:@selector(didOperation:oldRecord:newRecord:)]) {
            //更新后的模型
            NQRecord *recordModel = [NQRecord recordWithsickType:self.sickTypeLabel.text sickDetail:self.sickDetailLabel.text sickDesTags:self.sickDesTags sickDescribe:self.describeTextView.text picArr:self.picArr firstImage:self.firstImage postTime:self.postTime];
            [self.delegate didOperation:NQAddRecordVcTypePost oldRecord:self.recordSelectedModel newRecord:recordModel];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:confirmBtn];
    //取消按钮
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancel];
    
    //3.显示消息框
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - sickPicView
- (void)setupSickPicView{
    CGFloat picX = 0;
    CGFloat picY = 0;
    CGFloat picW = NQPicW;
    CGFloat picH = picW;
    CGFloat margin = 10;
    for (NSInteger i = 0; i < self.picArr.count; ++i) {
        picX = (picW + margin) * i;
        UIView *btn = self.picArr[i];
        btn.userInteractionEnabled = YES;
        btn.frame = CGRectMake(picX, picY, picW, picH);
        [self.sickPicView addSubview:btn];
        if (i == self.picArr.count - 1) {
            [(UIButton*)btn addTarget:self action:@selector(addImage:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
}

//点击"加号"按钮
- (void)addImage:(UIButton *)addBtn{
    [self alertTip];
}

#pragma mark - 弹框提示
- (void)alertTip{
    //1.弹出提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"头像设置" message:@"请选择修改头像的方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    //2.添加按钮
    //从本地相册添加
    UIAlertAction *photoLibrary = [UIAlertAction actionWithTitle:@"本地相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self chooesIcon];
    }];
    [alert addAction:photoLibrary];
    //拍照添加
    UIAlertAction *Camera = [UIAlertAction actionWithTitle:@"拍摄照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self chooseCamera];
    }];
    [alert addAction:Camera];
    //取消按钮
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancel];
    
    //3.显示消息框
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 拍摄照片
- (void)chooseCamera{
    //创建图片选择器
    UIImagePickerController *picVc = [[UIImagePickerController alloc] init];
    //先检查相机是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //设置跳转类型
        picVc.sourceType = UIImagePickerControllerSourceTypeCamera;
       
        //设置代理
        picVc.delegate = self;
        //进行跳转
        [self.navigationController presentViewController:picVc animated:YES completion:nil];
    }
}

#pragma mark - 选择头像图片
- (void)chooesIcon{
    //创建图片选择器
    UIImagePickerController *picVc = [[UIImagePickerController alloc] init];
    //设置跳转类型 -- 所有相册
    picVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //设置代理
    picVc.delegate = self;
    //设置选择后的图片可被编辑
    picVc.allowsEditing = YES;
    //进行跳转
    [self presentViewController:picVc animated:YES completion:nil];
}

//相册的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary<NSString *,id> *)editingInfo{
    //选择图片之后,把图片插入到图片数据源中
    //绘制规定范围内的图片 -- 减小内存
    UIImage *img = [UIImage getScallImage:image];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:img];
    UIButton *deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(60, 0, 20, 20)];
    [deleteBtn setBackgroundImage:[UIImage imageNamed:@"compose_photo_close"] forState:UIControlStateNormal];
    [imageView addSubview:deleteBtn];
    [deleteBtn addTarget:self action:@selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
    [self.picArr insertObject:imageView atIndex:0];
    
    //设置setupSickPicView
    [self setupSickPicView];
    //实现dismiss方法
    [picker dismissViewControllerAnimated:NO completion:nil];
}

- (void)deleteImage:(UIButton *)deleteBtn{
    UIImageView *deletImageView = (UIImageView *)deleteBtn.superview;
    [deletImageView removeFromSuperview];
    [self.picArr removeObject:deletImageView];
    [self setupSickPicView];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    //实现dismiss方法
    [picker dismissViewControllerAnimated:NO completion:nil];
}


//设置文本框
- (void)setupTextView{
    //设置占位文字
    self.describeTextView.holdStr = NQHolder;
    // 当textView拖拽的时候 让键盘消失，只设置 onDarg是不行,还有下面一句话
    self.describeTextView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    //设置一下,textView的滚动方向
    self.describeTextView.alwaysBounceVertical = YES;
    //设置代理
    self.describeTextView.delegate = self;
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
    if ([self.describeTextView hasText]) {
        self.describeTextView.textColor = [UIColor blackColor];
        self.describeTextView.holdStr = @"";
    }else{
        self.describeTextView.holdStr = NQHolder;
    }
    self.sickDescribe = self.describeTextView.text;
    //重绘
    [self.describeTextView setNeedsDisplay];
}


#pragma mark - 点击事件
//点击确认 -- 把当前页面数据转成模型,传递给上一层,并归档数据
- (void)confirm{
    //当疾病类型和病例图片同时存在时,才会存档
    if (self.sickType&&self.firstImage) {
        NQRecord *recordModel = [NQRecord recordWithsickType:self.sickType sickDetail:self.sickDetail sickDesTags:self.sickDesTags sickDescribe:self.sickDescribe picArr:self.picArr firstImage:self.firstImage postTime:self.postTime];
        self.addRecrdModel(recordModel);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

//点击"疾病类型"
- (IBAction)sickTypeClick:(UIButton *)sender {
    OKSickTreatController *vc = [[OKSickTreatController alloc] init];
    vc.data = @[@"肿瘤", @"血液病", @"心脑血管病", @"神经系统", @"骨科"];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 疾病类型点击回调
- (void)surebtnClickCallBack:(NSInteger)treatType {
//    NSLog(@"%zd", treatType);
    self.sickTypeBtn.selected = YES;
    self.ci1_id = treatType - 1;
    NSArray *sickArray = @[@"肿瘤", @"血液病", @"心脑血管病", @"神经系统", @"骨科"];
    self.sickType = sickArray[self.ci1_id - 1];
    self.sickTypeLabel.text = self.sickType;
    
}

//点击"疾病细分"
- (IBAction)sickDetailClick:(UIButton *)sender {
    
    // 如果疾病类型未选择, 则无法选取
    if (self.sickTypeBtn.selected == NO) {
        [SVProgressHUD showErrorWithStatus:@"请先选择疾病类型"];
        return;
    }
    
    NSString *ci1_id = [NSString stringWithFormat:@"%zd", self.ci1_id];
    NSDictionary *params = @{@"page":@1,
                             @"page_size":@15,
                             @"ci1_id":ci1_id,
                             @"keyword":@""
                             };
    //   创建跳转控制器
    OKSickSearchController *searchController = [[OKSickSearchController alloc] init];
    searchController.params = params;
    searchController.delegate = self;
    [self.navigationController pushViewController:searchController animated:YES];
}

#pragma mark - 疾病细分按钮点击回调
- (void)sickSegmentCellClick:(OKSickModel *)model {
    self.sickDetail = model.ci3_name;
    self.sickDetailLabel.text = self.sickDetail;
}

//点击"添加病症描述标签"
- (IBAction)addDescribe:(NQDescribeBtn *)sender {
    OKSickDescVcTableViewController *vc = [[OKSickDescVcTableViewController alloc] init];
    vc.sickTags = self.sickDesTags;
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - 病症描述回调
- (void)sickDescVcCallBack:(NSArray *)callBack {
    //保存疾病标签
    self.sickDesTags = callBack;
    //移除sickDiscribeView的所有子控件
    for (UILabel *sub in self.sickDiscribeView.subviews) {
        [sub removeFromSuperview];
    }
    //默认sickViewHeight的约束
    self.sickViewHeight.constant = 30;
    //按顺序在sickDiscribeView中创建Label
    CGFloat labelH = NQSickLabelH;
    CGFloat labelW = 0;
    CGFloat labelX = 0;
    CGFloat labelY = 0;
    CGFloat witch = 0;
    CGFloat maxW = 0;
    for (NSInteger i = 0; i < callBack.count; ++i) {
        UILabel *sickLabel = [[UILabel alloc] init];
        sickLabel.text = callBack[i];
        sickLabel.textColor = NQNavColor;
        sickLabel.layer.borderWidth = 2;
        sickLabel.textAlignment = NSTextAlignmentCenter;
        sickLabel.layer.borderColor = NQNavColor.CGColor;
        [sickLabel sizeToFit];
        
        
        labelX = witch;
        labelW = sickLabel.frame.size.width;
        labelW += 8;
        
        sickLabel.frame = CGRectMake(labelX, labelY, labelW, labelH);
        
        [self.sickDiscribeView addSubview:sickLabel];
        
        witch += sickLabel.frame.size.width +10 ;
        maxW = witch + labelW;
        if (maxW > NQScreenW - 20) {
            witch = 0;
            labelY = 40;
            //改变sickViewHeight的约束
            self.sickViewHeight.constant = 70;
        }
        
//        NSLog(@"%@",NSStringFromCGRect(sickLabel.frame));
    }
    //强制布局
    [self.view layoutIfNeeded];
}



@end
